package pers.wchen.mybatis.generate.data.property;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @作者： wchen
 * @描述： 配置文件读取
 * @创建时间： 2018/2/9 14:25
 * @版本：Copyright 2018, Inc. All Rights Reserved.
 * @修改信息：
 */
public class PropertyManager {
    public static PropertyManager propertyManager = null;
    private InputStream is = null;
    private InputStreamReader isr = null;
    private BufferedReader br = null;
    private Map<String, String> dataMap = null;

    private PropertyManager(){

    }

    /**
     *  @描述: 读取配置文件并写入数据
     *  @参数： [path]
     *  @返回值： void
     *  @创建人: wchen
     *  @创建时间: 2018/2/9
     *  @修改人和其它信息:
     */
    private void read(String path){
        File file = new File(path);
        try {
            is = new FileInputStream(file);
            isr = new InputStreamReader(is, "GBK");
            br = new BufferedReader(isr);
            String temp = null;
            temp = br.readLine();
            while (temp != null) {
                if(temp.contains("=")) {
                    int start = temp.indexOf("=");
                    dataMap.put(temp.substring(0, start), temp.substring(start+1, temp.length()));
                }
                temp = br.readLine();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                br.close();
                isr.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     *  @描述: 获取生成的配置数据
     *  @参数： [path]
     *  @返回值： java.util.Map<java.lang.String,java.lang.String>
     *  @创建人: wchen
     *  @创建时间: 2018/2/9
     *  @修改人和其它信息:
     */
    public Map<String, String> getConfigMap(String path) {
        if(dataMap == null){
            dataMap = new HashMap<String, String>();
            read(path);
        }
        return this.dataMap;
    }

    /**
     *  @描述: 单例
     *  @参数： []
     *  @返回值： pers.wchen.mybatis.generate.data.property.PropertyManager
     *  @创建人: wchen
     *  @创建时间: 2018/2/10
     *  @修改人和其它信息:
     */
    public static PropertyManager newInstance(){

        if(propertyManager == null){
            propertyManager = new PropertyManager();
        }
        return propertyManager;
    }


    public static void main(String[] args) {
        String str = "datasource.url=jdbc:mysql://123.206.176.29:3306/weishier_deploy??autoConnect=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=UTC";
        int start = str.indexOf("=");
        System.out.println("start :" + start);
        System.out.println(str.substring(0, start));
        System.out.println(str.substring(start+1, str.length()));
    }

}
